package com.dayuanit.dy16.atm.ws;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AtmTextWebSocketHandler extends TextWebSocketHandler {

    //key=用户ID  value=WebSocketSession
//    private Map<Long, WebSocketSession> clientSessions = new HashMap<>();//HashMap不是线程安全的。
//    private Map<Long, WebSocketSession> clientSessions = new Hashtable<>();//Hashtable线程安全，但是完全串行化，性能不高。
    private Map<Long, WebSocketSession> clientSessions = new ConcurrentHashMap<>();//JUC包下面的线程安全的Map集合，性能也比Hashtable高很多。


    public void sendMsg(String msg, long userId) {
        WebSocketSession webSocketSession = clientSessions.get(userId);
        try {
            webSocketSession.sendMessage(new TextMessage(msg));
            System.out.println(">>>>发送消息：" + msg);
        } catch (IOException e) {
            e.printStackTrace();
            if (webSocketSession != null) {
                clientSessions.remove(userId);
                if (webSocketSession.isOpen()) {
                    try {
                        webSocketSession.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 握手成功之后 调用的方法
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("websocket握手成功");
        long userId = (long)session.getAttributes().get("userId");

        clientSessions.put(userId, session);
    }

    /**
     * 接收客户端消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("客户端发送的消息：" + payload);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("websocket连接断掉");
        long userId = (long)session.getAttributes().get("userId");
        clientSessions.remove(userId);
    }
}
